﻿using System;
using System.Collections.Generic;
using Ones.Models;

using TweetSharp.Twitter.Service;
using TweetSharp;
using TweetSharp.Model;

using System.Diagnostics;
using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

namespace Ones.ViewModels
{
    class AuthorizationViewModel
    {
        private TwitterService _service;
        private FileStream _str;
        private BinaryFormatter _reader = new BinaryFormatter();

        private bool _authenticated = false;
        public virtual event EventHandler Authenticated;
        public virtual event EventHandler Load;

        public Boolean IsAuthenticated
        {
            get { return _authenticated; }
            set
            {
                _authenticated = value;
                if (_authenticated)
                {
                    Authenticated.Invoke(this, null);
                }
            }
        }

        public AuthorizationViewModel()
        {
            TwitterClientInfo info = new TwitterClientInfo();

            info.ConsumerKey = "EMC0ylip9jKZjfY2JQE4rQ";
            info.ConsumerSecret = "ImlOrAa0jZukYA6UT9trMlWENb4fadjfLDvgjUaQPTM";

            _service = new TwitterService(info);
        }

        public void Start()
        {
            this.Load.Invoke(this, null);
        }

        public OAuthToken AskAuthorization()
        {
            OAuthToken requestToken = _service.GetRequestToken();

            Uri uri = new Uri(_service.GetAuthorizationUrl(requestToken));
            Process.Start(uri.ToString());

            return requestToken;
        }

        public TwitterService AuthenticateUserLocal()
        {
            _str = new FileStream("users.ones", FileMode.Open);
            _reader = new BinaryFormatter();

            TwitterService service = null;

            List<User> users = (List<User>)_reader.Deserialize(_str);

            _str.Close();


            foreach (User user in users)
            {
                if (user.Primary)
                {
                    service = this.AuthorizeWithTokens(user.AccessToken, user.SecretToken);

                    _str.Close();
                }
            }

            return service;
        }

        public TwitterService Authorize(OAuthToken requestToken, string pin)
        {
            OAuthToken access = _service.GetAccessToken(requestToken, pin);

            this.SaveUserAccess(access);

            _service.AuthenticateWith(access.Token, access.TokenSecret);

            return _service;
        }

        private TwitterService AuthorizeWithTokens(string token, string tokenSecret)
        {
            _service.AuthenticateWith(token, tokenSecret);

            return _service;
        }

        private void SaveUserAccess(OAuthToken access)
        {
            string filename = "users.ones";
            List<User> users;
            User user;

            try
            {
                _str = new FileStream(filename, FileMode.Open);
                users = (List<User>)_reader.Deserialize(_str);
                user = new User();
                user.Primary = false;
            }
            catch (FileNotFoundException ex)
            {
                _str = new FileStream(filename, FileMode.Create);
                users = new List<User>();
                user = new User();
                user.Primary = true;
                Console.WriteLine(ex.Message);
            }
                        
            user.Username = access.ScreenName;
            user.UserId = access.UserId;
            user.AccessToken = access.Token;
            user.SecretToken = access.TokenSecret;

            users.Add(user);

            _reader.Serialize(_str, users);
            _str.Close();
        }        
    }
}
